const _ = require('lodash');
const async = require('async');
const LoopBackContext = require('loopback-context');
const services = require('../../services');

const eLancoService = services.eLanco;

module.exports = (ctx, modelInstance, callback) => {
  const context = LoopBackContext.getCurrentContext();
  const req = ctx.req;
  const id = req.params.id;
  const formId = req.body.formId;
  const data = req.body.formDetail;
  async.parallel({
    form: async.apply(eLancoService.getFormIncludeAll, formId),
    formDetail: async.apply(eLancoService.getFormDetailIncludeAll, formId, id),
  }, (error, result) => {
    if (error) return callback(error);
    const { form, formDetail } = result;
    const flow = form.flow();
    const eventName = flow.flowRun.events.rejectBefore;
    formDetail.formDetail = data;
    context.set('form', form);
    context.set('flow', flow);
    context.set('formDetail', formDetail);
    if (_.isEmpty(eventName)) return callback();
    eLancoService.handleCustomEvent(form, formDetail, eventName, callback);
    eLancoService.handleCustomEvent(form, formDetail, flow.flowRun.events.rejectBefore, callback);
  });
};
